﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace pdfer.Filters
{
    internal class ASCIIHexDecodeFilter : IFilter
    {
        /// <summary>
        /// <inheritdoc/>
        /// 线程安全的实现
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Byte[] Decode(ReadOnlySpan<Byte> input)
        {
            using var output = new MemoryStream();
            Int32 tmp =0;
            for(var i = 0; i < input.Length; i++)
            {
                var data = input[i];
                if(data == (Byte)'>')
                {
                    break;
                }
                if(data is (0 or 9 or 10 or 12 or 13 or 32))
                {
                    continue;
                }
                var _ = GetHex(data);
                if(i % 2 == 0)
                {
                    tmp = _;
                }
                else
                {
                    output.WriteByte((Byte)((tmp << 4) +_));
                }
            }
            if(input.Length % 2 == 1)
            {
                // 奇数个 后面补00
                output.WriteByte((Byte)((tmp << 4) + 0));
            }
            return output.ToArray();
        }

        private static Byte GetHex(Byte v)
        {
            if(v >= '0' && v <= '9')
            {
                return (Byte)(v - '0');
            }
            if(v >= 'A' && v <= 'F')
            {
                return (Byte)(v - 'A' + 10);
            }
            if (v >= 'a' && v <= 'f')
            {
                return (Byte)(v - 'a' + 10);
            }
            throw new Exception("非法字符：ASCIIHexDecode");
        }

        /// <inheritdoc/>
        public byte[] Encode(ReadOnlySpan<Byte> input)
        {
            throw new NotImplementedException();
        }
    }
}
